<template>
  <div class="goods-params-container">
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ name: 'welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="
注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <el-row class="margin-opt">
        <el-col>
          <span>选择商品分类&nbsp;&nbsp;</span>
          <el-cascader
            v-model="selectedCateKeys"
            :options="goodsCateList"
            :props="goodsCateProps"
            @change="goodsCateHandleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 切换面板 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数 -->
          <el-table :data="manyTableData" style="width: 100%" border>
            <el-table-column type="expand" label="展开">
              <template v-slot="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  :disable-transitions="true"
                  @close="closeTag(scope.row, index)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  type="primary"
                  plain
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  class="el-icon-edit"
                  size="mini"
                  type="primary"
                  @click="editParams(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  class="el-icon-delete"
                  size="mini"
                  type="danger"
                  @click="deleteParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态属性 -->
          <el-table :data="onlyTableData" style="width: 100%" border>
            <el-table-column type="expand" label="展开">
              <template v-slot="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  :disable-transitions="true"
                  @close="closeTag(scope.row, index)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  type="primary"
                  plain
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column
              prop="attr_name"
              label="属性名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  class="el-icon-edit"
                  size="mini"
                  type="primary"
                  @click="editParams(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  class="el-icon-delete"
                  size="mini"
                  type="danger"
                  @click="deleteParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加动态参数和静态属性对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="dialogVisibleColsed"
    >
      <el-form :model="addForm" ref="ruleFormRef" label-width="80px">
        <el-form-item
          :label="titleText"
          prop="attr_name"
          :rules="{
            required: true,
            message: `请输入${this.titleText}`,
            trigger: 'blur'
          }"
        >
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsOnConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改动态参数和静态属性 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="dialogVisibleColsed"
    >
      <el-form :model="editForm" ref="ruleFormRef" label-width="80px">
        <el-form-item
          :label="titleText"
          prop="attr_name"
          :rules="{
            required: true,
            message: `请输入${this.titleText}`,
            trigger: 'blur'
          }"
        >
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsOnConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getGoodsCateAPI,
  getGoodsParamsListAPI,
  addParamsAPI,
  getParamsByIdAPI,
  editParamsAPI,
  deleteParamsByIdAPI
} from '@/api'
export default {
  name: 'GoodsParams',
  data() {
    return {
      goodsCateList: [],
      goodsCateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      selectedCateKeys: [],
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      editForm: {
        attr_name: ''
      },
      attrId: ''
    }
  },
  created() {
    this.loadingGoodsCateList()
  },
  methods: {
    //   加载所有商品分类
    async loadingGoodsCateList() {
      try {
        const { data } = await getGoodsCateAPI()
        if (data.meta.status !== 200) {
          return this.$message.error('加载商品分类列表数据失败')
        }
        this.goodsCateList = data.data
        this.$message.success('加载商品分类列表数据成功')
      } catch (err) {
        this.$message.error('加载商品分类列表数据失败')
      }
    },
    // 获取参数列表
    async getParamsList() {
      if (this.selectedCateKeys.length !== 3) {
        this.manyTableData = []
        this.onlyTableData = []
        this.selectedCateKeys = []
        return
      }
      // 当选项发生变化，则请求接口，获取相应数据
      try {
        const { data } = await getGoodsParamsListAPI(
          this.cartId,
          this.activeName
        )
        if (data.meta.status !== 200) {
          return this.$message.error('获取参数列表失败')
        }
        data.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          item.inputVisible = false
          item.inputValue = ''
        })
        // console.log(data.data)
        if (this.activeName === 'many') {
          this.manyTableData = data.data
          //   console.log(this.manyTableData)
        } else {
          this.onlyTableData = data.data
          //   console.log(this.onlyTableData)
        }
      } catch (err) {
        this.$message.error('获取参数列表失败')
      }
    },
    // 商品分类改变处理函数
    async goodsCateHandleChange() {
      this.getParamsList()
    },
    // 侦听切换事件
    async handleTabClick() {
      this.getParamsList()
    },
    // 监听对话框关闭事件
    dialogVisibleColsed() {
      this.$refs.ruleFormRef.resetFields()
    },
    // 添加参数确认事件
    addParamsOnConfirm() {
      this.$refs.ruleFormRef.validate(async valid => {
        if (!valid) return
        try {
          const { data } = await addParamsAPI(this.cartId, {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          })
          if (data.meta.status !== 201) {
            return this.$message.error('添加参数失败')
          }
          this.$message.success('添加参数成功')
          this.addDialogVisible = false
          this.getParamsList()
        } catch (err) {
          this.$message.error('添加参数失败')
        }
      })
    },
    // 修改参数
    async editParams(attrId) {
      this.attrId = attrId
      try {
        const { data } = await getParamsByIdAPI(this.cartId, attrId, {
          attr_sel: this.activeName
        })
        if (data.meta.status !== 200) {
          return this.$message.error('获取参数失败')
        }
        this.$message.success('获取参数成功')
        this.editForm.attr_name = data.data.attr_name
        this.editDialogVisible = true
      } catch (err) {
        this.$message.error('获取参数失败')
      }
    },
    // 修改参数确认事件
    editParamsOnConfirm() {
      // 预校验
      this.$refs.ruleFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        try {
          const { data } = await editParamsAPI(this.cartId, this.attrId, {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          })
          if (data.meta.status !== 200) {
            return this.$message.error('修改参数失败')
          }
          this.$message.success('修改参数成功')
          this.editDialogVisible = false
          this.getParamsList()
        } catch (error) {
          this.$message.error('修改参数失败')
        }
      })
    },
    // 删除参数
    async deleteParams(attrId) {
      const res = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (res !== 'confirm') {
        return this.$message.info('已取消删除该参数操作')
      }
      // 删除参数 ，渲染页面
      try {
        const { data } = await deleteParamsByIdAPI(this.cartId, attrId)
        if (data.meta.status !== 200) {
          return this.$message.error('删除参数失败')
        }
        this.$message.success('删除参数成功')
        this.getParamsList()
      } catch (error) {
        this.$message.error('删除参数失败')
      }
    },
    // 标签失去焦点， 或点击 enter 触发事件
    async handleInputConfirm(row) {
      // console.log(val)
      if (!row.inputValue.trim()) {
        row.inputValue = ''
        row.inputVisible = false
        return true
      }
      // 若有内容，则追加进标签内
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 发起请求。存数据
      this.saveAttrVal(row)
    },
    // 展示 input 表单
    showInput(row) {
      row.inputVisible = true
      // console.log(this)
      // 自动聚焦
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 关闭标签
    async closeTag(row, index) {
      row.attr_vals.splice(index, 1)
      this.saveAttrVal(row)
    },
    // 保存属性值
    async saveAttrVal(row) {
      try {
        const { data } = await editParamsAPI(this.cartId, row.attr_id, {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        })
        if (data.meta.status !== 200) {
          return this.$message.error('编辑参数失败')
        }
        this.$message.success('编辑参数成功')
      } catch (error) {
        this.$message.error('编辑参数失败')
      }
    }
  },
  computed: {
    isBtnDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true
      }
      return false
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    },
    cartId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    }
  }
}
</script>

<style scoped lang="less">
.goods-params-container {
  .margin-opt {
    margin: 15px 0;
  }
  .el-tag {
    margin: 10px;
  }
  /deep/.input-new-tag {
    width: 120px;
  }
}
</style>
